package com.fadadianqi.mall.product.service;

import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.commons.PrimaryKeyCreator;
import com.fadadianqi.mall.model.Nav;
import com.fadadianqi.mall.product.ProductException;
import com.fadadianqi.mall.product.dao.ItemSPUAttrDAO;
import com.fadadianqi.mall.product.dao.ItemSPUDAO;
import com.fadadianqi.mall.product.dao.NavBrandDAO;
import com.fadadianqi.mall.product.dao.NavItemSPUDAO;
import com.fadadianqi.mall.product.model.*;
import com.fadadianqi.mall.service.NavService;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.ValidatorHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by aroot on 2/7/14.
 */
@Service
public class ItemSPUService {

    @Autowired
    private ItemSPUDAO itemSPUDAO;
    @Autowired
    private NavBrandDAO navBrandDAO;
    @Autowired
    private NavItemSPUDAO navItemSPUDAO;
    @Autowired
    private ItemSPUAttrDAO itemSPUAttrDAO;
    @Autowired
    private NavService navService;
    @Autowired
    private AttrService attrService;

    private ItemSPUAttr getItemSPUAttr(String spuId, String valId) {
        return itemSPUAttrDAO.getByIdAndValId(spuId, valId);
    }

    public ItemSPU getById(String id) {
        return itemSPUDAO.getById(id);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void save(SPUForm form) throws ProductException {
        if (ValidatorHelper.isEmpty(form.getName())
                || ValidatorHelper.isEmpty(form.getDisplayName())) {
            throw new ProductException("exception.mall.product.name&&displayName.required");
        } else if (ValidatorHelper.isEmpty(form.getBrandId())) {
            throw new ProductException("exception.mall.product.brand.required");
        } else if (ValidatorHelper.isEmpty(form.getCurrentNavId())) {
            throw new ProductException("exception.mall.product.navId.required");
        }
        if (ValidatorHelper.isEmpty(form.getId())) {
            form.setId(PrimaryKeyCreator.create());
            itemSPUDAO.create(form);
        } else {
            ItemSPU spu = getById(form.getId());
            spu.setUpdateTime(new Date());
            spu.setName(form.getName());
            spu.setDisplayName(form.getDisplayName());
            spu.setDetails(form.getDetails());
            spu.setAttrValsId(form.getAttrValsId());
            spu.setBrandId(form.getBrandId());
            itemSPUDAO.update(spu);
            form.setId(spu.getId());
        }
        itemSPUAttrDAO.removeBySpuId(form.getId());
        List<String> vals = (List<String>) JSONProvider.toBean(form.getAttrValsId(), ArrayList.class);
        //Map<String, AttrName> cache = new HashMap<String, AttrName>();
        if (ValidatorHelper.isNotEmpty(vals)) {
            for (String val : vals) {
                AttrVal attrVal = attrService.getAttrValById(val);
                /*AttrName attrName = cache.get(attrVal.getAttrNameId());
                if(attrName == null) {
                    attrName = attrService.getAttrNameById(attrVal.getAttrNameId());
                    cache.put(attrName.getId(), attrName);
                }*/
                ItemSPUAttr isa = getItemSPUAttr(form.getId(), attrVal.getId());
                if (isa == null) {
                    isa = new ItemSPUAttr();
                    isa.setSpuId(form.getId());
                    isa.setId(PrimaryKeyCreator.create());
                    isa.setAttrNameId(attrVal.getAttrNameId());
                    isa.setAttrValId(attrVal.getId());
                    itemSPUAttrDAO.create(isa);
                }
            }
        }
        afterSave(form);
    }

    private void afterSave(SPUForm spu) {
        // 目前导航分类同一级别属于一对一关系，以后扩展。
        navItemSPUDAO.removeBySpuId(spu.getId());
        /*
         * 记录spu和导航分类的对应关系
         */
        String currentNavId = spu.getCurrentNavId();
        Nav nav = navService.getById(currentNavId);
        if (ValidatorHelper.isEmpty(nav)) {
            return;
        }
        Nav rootNav = navService.getById(nav.getRootId());
        if (null == rootNav) {
            rootNav = nav;
        }
        List<Nav> navList = navService.showTreeBranchs(currentNavId);
        NavItemSPU nis = navItemSPUDAO.getByNavIdAndSPUId(rootNav.getId(), spu.getId());
        if (null == nis) {
            nis = new NavItemSPU();
            nis.setId(PrimaryKeyCreator.create());
            nis.setNavId(rootNav.getId());
            nis.setSpuId(spu.getId());
            navItemSPUDAO.create(nis);
            // 开始记录Nav和品牌的对应关系
            NavBrand nb = navBrandDAO.getByNavIdAndBrandId(rootNav.getId(), spu.getBrandId());
            if (nb == null) {
                nb = new NavBrand();
                nb.setNavId(rootNav.getId());
                nb.setBrandId(spu.getBrandId());
                nb.setId(PrimaryKeyCreator.create());
                nb.setOrderby(1);
                navBrandDAO.create(nb);
            } else {
                nb.setOrderby(nb.getOrderby() + 1);
                navBrandDAO.update(nb);
            }
        }
        for (Nav _nav : navList) {
            NavItemSPU _nis = navItemSPUDAO.getByNavIdAndSPUId(_nav.getId(), spu.getId());
            if (null == _nis) {
                _nis = new NavItemSPU();
                _nis.setId(PrimaryKeyCreator.create());
                _nis.setNavId(_nav.getId());
                _nis.setSpuId(spu.getId());
                navItemSPUDAO.create(_nis);
                // 开始记录Nav和品牌的对应关系
                NavBrand nb = navBrandDAO.getByNavIdAndBrandId(_nav.getId(), spu.getBrandId());
                if (nb == null) {
                    nb = new NavBrand();
                    nb.setNavId(_nav.getId());
                    nb.setBrandId(spu.getBrandId());
                    nb.setId(PrimaryKeyCreator.create());
                    nb.setOrderby(1);
                    navBrandDAO.create(nb);
                } else {
                    nb.setOrderby(nb.getOrderby() + 1);
                    navBrandDAO.update(nb);
                }
            }
        }
        // logic end
    }

    public List<ItemSPU> findAll(Pagination pagination) {
        List<ItemSPU> spuList = itemSPUDAO.findAll(pagination);

        return spuList;
    }

    public int countAll() {
        return itemSPUDAO.countAll();
    }

    public int countAllNotIndexed() {
        return itemSPUDAO.countAllNotIndexed();
    }

    public List<ItemSPU> findAllNotIndexed(Pagination pagination) {
        return itemSPUDAO.findAllNotIndexed(pagination);
    }

    public void updateIsIndexed(ItemSPU spu) {
        itemSPUDAO.update(spu);
    }

    public static class SPUForm extends ItemSPU {

        private String currentNavId;

        public String getCurrentNavId() {
            return currentNavId;
        }

        public void setCurrentNavId(String currentNavId) {
            this.currentNavId = currentNavId;
        }
    }
}
